import { login, getInfo, getDetailInfo } from "@/api/user";
import { getToken, setToken, removeToken } from "@/utils/auth"; //  setToken,
// import { resetRouter } from "@/router";
import router from "@/router";

const getDefaultState = () => {
  return {
    token: getToken(),
    name: "",
    avatar: "",
    userinfo: null,
  };
};

const state = getDefaultState();

const mutations = {
  upDateUserInfo: (state, info) => {
    state.userinfo = info;
  },
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState());
  },
  SET_TOKEN: (state, token) => {
    state.token = token;
  },
  SET_NAME: (state, name) => {
    state.name = name;
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar;
  },
};

const actions = {
  // user login
  async login({ commit }, form) {
    try {
      // context类似于$store
      // payload是触发action时传递的参数
      const ret = await login({
        mobile: form.username,
        password: form.password,
      });
      if (ret.code === 10000) {
        // 登录成功,先保存到state里面，再缓存token到本地存储
        commit("SET_TOKEN", ret.data);
        setToken(ret.data);
        return Promise.resolve(true);
      } else {
        // 登录失败
        return Promise.reject(false);
      }
    } catch (error) {
      return Promise.reject(false);
    }
  },

  // 获取用户信息
  async getInfo({ commit }) {
    const baseUserInfo = await getInfo();
    const baseUserDetail = await getDetailInfo(baseUserInfo.data.userId);
    if (baseUserInfo.code === 10000) {
      commit("upDateUserInfo", {
        ...baseUserInfo.data,
        ...baseUserDetail.data,
      });
    }
  },
  // 退出登录
  logout({ commit }) {
    // 1.清空store中的token
    // 2.清空本地存储的token
    // 3.跳转登录页
    commit("SET_TOKEN", "");
    commit("upDateUserInfo", null);
    removeToken();
    router.push("/login");
  },

  // remove token
  resetToken({ commit }) {
    return new Promise((resolve) => {
      removeToken(); // must remove  token  first
      commit("RESET_STATE");
      removeToken();
    });
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
